package com.wanxing.sellerapp.platform

import android.annotation.SuppressLint
import android.os.Build
import android.util.Log
import androidx.annotation.WorkerThread
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.TypeReference
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.SPUtils
import com.github.kittinunf.fuel.core.extensions.jsonBody
import com.github.kittinunf.fuel.httpDownload
import com.github.kittinunf.fuel.httpPost
import com.github.kittinunf.result.Result
import com.wanxing.sellerapp.config.AppConfig
import com.wanxing.sellerapp.platform.entity.ApiResult
import com.wanxing.sellerapp.platform.entity.CreateOrderResponse
import com.wanxing.sellerapp.platform.entity.Seller
import com.wanxing.sellerapp.seller.events.ShowLogEvent
import org.greenrobot.eventbus.EventBus
import java.io.File

object Api {

    var onAdvUrlChange: ((String) -> Unit)? = null


    /**
     * 启动程序时注册设备到平台。若注册失败，则一直注册直到成功
     */

    @WorkerThread
    fun register(): Seller? {
        val data = JSONObject()
        data["uid"] = getSN()
        data["appVersionCode"] = AppUtils.getAppVersionName()
        // 称重机 3288芯片， 视频机： 其他芯片
        data["version"] =  if (DeviceUtils.getModel() == "rk3288") "2" else "3"
        val url ="${AppConfig.DEFAULT_SERVICE_URL}/seller/device/register"
        val (_, _, result) = url
            .httpPost()
            .timeout(3000).jsonBody(data.toJSONString()).responseString()
        return when (result) {
            is Result.Failure -> {
                Log.e(AppConfig.LOGTAG, result.toString(),result.error)
                null
            }
            is Result.Success -> {
                val respJson = JSON.parseObject(result.get())
                if (!respJson.getBoolean("success")) {
                    Log.d("Api", respJson.toString())
                    null
                } else {
                    JSON.parseObject(JSON.toJSONString(respJson["result"]), Seller::class.java)
                }
            }
        }
    }

    @WorkerThread
    fun updateDeviceStatus(camera1State: Boolean, camera2State: Boolean, power: Boolean) {
        val data = JSONObject()
        data["sn"] = getSN()
        data["c1s"] = camera1State
        data["c2s"] = camera2State
        data["ps"] = power
        val (_, _, result) = "${AppConfig.DEFAULT_SERVICE_URL}/seller/device/deviceStatus".httpPost()
            .timeout(3000).jsonBody(data.toJSONString()).responseString()
        when (result) {
            is Result.Failure -> Log.e(AppConfig.LOGTAG, result.toString(), result.error)
            is Result.Success -> {
                val respJson = JSON.parseObject(result.get())
                //保存广告地址
                val url = respJson.getString("result") ?: ""
                val old = AppConfig.getAdvUrl()
                if ("" != url && old != url) {
                    SPUtils.getInstance().put("advUrl", url)
                    onAdvUrlChange?.invoke(url)
                }
            }
        }
    }

    fun getAdvPath(url: String): String {
        val filename = url.split("/").last()
        val path = AppConfig.ADV_SAVE_PATH + filename
        val dir = File(AppConfig.ADV_SAVE_PATH)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        val existFiles = dir.listFiles()
        existFiles?.let {
            for (existFile in it) {
                val name = existFile.name
                if (name != filename) {
                    existFile.delete()
                } else {
                    return@getAdvPath path
                }
            }
        }
        return if (File(path).exists()) {
            path
        } else{
            while (!downloadAdvVideo(url,path)){}
            path
        }
    }

    private fun downloadAdvVideo(url: String, path: String): Boolean{
        val(_,_,result) = url.httpDownload()
            .fileDestination { _, _ -> File(path) }
            .response()
        return when (result) {
            is Result.Failure ->  {
                EventBus.getDefault().post(ShowLogEvent("下载广告视频失败: ${result.error}", ""))
                false
            }
            is Result.Success -> true
        }
    }

    /**
     * 饭卡下单
     */
    @WorkerThread
    fun balanceOrder(cardNo:String): CreateOrderResponse {
        val data = JSONObject()
        data["sn"] = getSN()
        data["cardNo"] = cardNo
        data["door"] = 1
        // 称重机 3288芯片， 视频机： 其他芯片
        val (_, _, result) = "${AppConfig.DEFAULT_SERVICE_URL}/seller/device/balanceOrder".
        httpPost().timeout(1000).jsonBody(data.toJSONString()).responseString()
        return when (result) {
            is Result.Failure -> {
                Log.e(AppConfig.LOGTAG, result.toString(),result.error)
                return CreateOrderResponse("-1", "网络异常", "", "")
            }
            is Result.Success -> {
                val rlt:ApiResult<CreateOrderResponse> = JSON.parseObject(result.get(),
                    object :TypeReference<ApiResult<CreateOrderResponse>>(){}.type)
                if (rlt.isSuccess) {
                    rlt.result
                }else{
                    CreateOrderResponse("500", "系统异常", "", "")
                }
            }
        }

    }

    fun updateOrder(orderId: String, status: String): Boolean {
        val data = JSONObject()
        data["orderId"] = orderId
        data["status"] = status
        val (_, _, result) = "${AppConfig.DEFAULT_SERVICE_URL}/seller/device/updateOrder"
            .httpPost().timeout(1000).jsonBody(data.toJSONString()).responseString()
        return when (result) {
            is Result.Failure -> {
                EventBus.getDefault().post(ShowLogEvent("同步订单状态失败：${result.error}", orderId))
                return false
            }
            is Result.Success -> {
                val rlt: ApiResult<Any> = JSON.parseObject(result.get(),
                    object : TypeReference<ApiResult<Any>>() {}.type
                )
                rlt.isSuccess
            }
        }

    }

    fun updateVideo(orderId: String, type: String): Boolean {
        val data = JSONObject()
        data["orderId"] = orderId
        data["type"] = type
        val (_, _, result) = "${AppConfig.DEFAULT_SERVICE_URL}/seller/device/updateOrderVideo"
            .httpPost().timeout(1000).jsonBody(data.toJSONString()).responseString()
        return when (result) {
            is Result.Failure -> {
                Log.e(AppConfig.LOGTAG, result.toString(),result.error)
                return false
            }
            is Result.Success -> {
                val rlt: ApiResult<Any> = JSON.parseObject(result.get(),
                    object : TypeReference<ApiResult<Any>>() {}.type
                )
                rlt.isSuccess
            }
        }

    }

    @SuppressLint("MissingPermission")
    private fun getSN() = if (Build.VERSION.SDK_INT < 26) {
        Build.SERIAL
    } else {
        Build.getSerial()

    }
}